package com.hksj.cbm.service;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hksj.cbm.dto.DeviceModelDTO;
import com.hksj.cbm.entity.DeviceModel;
import com.hksj.cbm.enums.DepartmentEnum;
import com.hksj.cbm.enums.ModelCategoryEnum;
import com.hksj.cbm.enums.StatusEnum;
import com.hksj.cbm.mapper.DeviceModelMapper;
import com.hksj.cbm.query.DeviceModelQuery;
import com.hksj.cbm.vo.DeviceModelExportVO;
import com.hksj.cbm.vo.DeviceModelVO;
import com.hksj.cbm.vo.SpaceModelVO;
import com.hksj.common.core.common.SpecialityModelCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author zengke
 * @version 1.0
 * @see DeviceModelService
 * @since 2024/7/11 14:57
 */

@Service
public class DeviceModelService extends ServiceImpl<DeviceModelMapper, DeviceModel> {

    @Autowired
    private SpaceModelService spaceModelService;

    @Autowired
    private DeviceInstanceService deviceInstanceService;

    /**
     * 新增设备模型
     */
    @Transactional
    public String createDeviceModel(DeviceModelDTO deviceModelDTO){

//        //通过设备模型查询专业模型id
//        Long specialityModelId = deviceInstanceService.getBaseMapper().querySpecialityOfDevice(deviceModelDTO.getDeviceId());

        //将DeviceModelDTO类型转为 DeviceModel
        DeviceModel deviceModel = Convert.convert(DeviceModel.class, deviceModelDTO);

//        //设置设备模型的专业模型
//        deviceModel.setSpecialityModelId(specialityModelId);

        //新增设备模型
        super.save(deviceModel);

        return "新增成功";
    }

    /**
     * 更新设备模型
     */
    @Transactional
    public String updateDeviceModel(DeviceModelDTO deviceModelDTO){

//        //通过设备模型查询专业模型id
//        Long specialityModelId = deviceInstanceService.getBaseMapper().querySpecialityOfDevice(deviceModelDTO.getDeviceId());

        //将DeviceModelDTO类型转为 DeviceModel
        DeviceModel deviceModel = Convert.convert(DeviceModel.class, deviceModelDTO);

//        //设置设备模型的专业模型
//        deviceModel.setSpecialityModelId(specialityModelId);

        //更新设备模型
        super.updateById(deviceModel);

        return "更新成功";
    }

    /**
     * 删除设备模型
     */
    @Transactional
    public String deleteDeviceModel(Long id){

        //查询设备模型
        DeviceModel deviceModel = super.getById(id);

        //判断设备模型是否存在
        if (ObjectUtils.isEmpty(deviceModel)){
            throw new RuntimeException("设备模型不存在,请刷新后重试");
        }

        //删除设备模型
        super.removeById(id);

        return "删除成功";
    }

    /**
     * 分页查询设备模型列表
     */
    public Page<DeviceModelVO> queryDeviceModelListByPaging(DeviceModelQuery deviceModelQuery){

        //综合驾驶舱查询所有设备 TODO:由于综合驾驶舱与其他专业不同、需要展示特定的几个专业的设备、可以查询出这几个专业下的所有设备然后自行做选择
        if (Objects.equals(deviceModelQuery.getSpecialityModelCode(), "ZHJSC")){
            deviceModelQuery.setSpecialityModelCode("");
        }

        //判断空间模型id集合不为空
        Assert.notNull(deviceModelQuery.getSpaceModelId(),"请先选择空间模型");

        //通过空间模型id查询子空间集合
        List<Long> childSpaceModelIdList = spaceModelService.querySpaceModelChildren(deviceModelQuery.getSpaceModelId()).stream().map(SpaceModelVO::getId).collect(Collectors.toList());

        deviceModelQuery.setChildSpaceModelIdList(childSpaceModelIdList);

        //创建分页实例
        Page<DeviceModelVO> page = new Page<>(deviceModelQuery.getPageNum(),deviceModelQuery.getPageSize());

        //分页查询
        List<DeviceModelVO> deviceModelList = baseMapper.queryDeviceListByPaging(page, deviceModelQuery);

        //获取设备模型集合 对应的 paths构成的集合
        List<String> pathsList = deviceModelList.stream().map(DeviceModelVO::getPaths).collect(Collectors.toList());

        //若paths集合不为空 设置设备id的路径集合
        if (!ObjectUtils.isEmpty(pathsList)){
            //查询路径map
            Map<String, List<SpaceModelVO>> pathsMap = deviceInstanceService.devicePathConvertToUTF8(pathsList);

            //设置空间模型信息
            deviceModelList.forEach(deviceModelVO -> {

                //获取设备对应的路径
                List<SpaceModelVO> spaceModelList = pathsMap.get(deviceModelVO.getPaths());

                //设置设备的路径集合
                deviceModelVO.setSpaceModelList(spaceModelList);
            });
        }

        //将设备列表设置到分页
        page.setRecords(deviceModelList);

        return page;
    }

    public void exportDeviceModel(DeviceModelQuery deviceModelQuery, HttpServletResponse response){

        //查询实验室所有的设备模型
        deviceModelQuery.setPageNum(1L);
        deviceModelQuery.setPageSize(2000L);

        //获取设备模型列表
        List<DeviceModelVO> deviceModelVOList = queryDeviceModelListByPaging(deviceModelQuery).getRecords();

        //若设备模型列表为空直接返回
        if (ObjectUtils.isEmpty(deviceModelVOList)){
            return;
        }

        //将设备模型VO列表 转换为 设备模型导出VO列表
        List<DeviceModelExportVO> data = deviceModelVOList.stream().map(deviceModelVO -> {
            DeviceModelExportVO deviceModelExportVO = new DeviceModelExportVO();

            //设置设备模型名称
            deviceModelExportVO.setDeviceModelName(deviceModelVO.getModelName());

            //设备的所属空间模型列表
            List<SpaceModelVO> spaceModelList = deviceModelVO.getSpaceModelList();
            if (!ObjectUtils.isEmpty(spaceModelList)) {
                //获取空间模型列表中每个对象 拼接空间模型名称
                String spaceModelName = spaceModelList.stream().map(SpaceModelVO::getModelName).collect(Collectors.joining());

                //设置所属建筑名称
                deviceModelExportVO.setOfBuildingName(spaceModelName);
            }

            //设置楼层科室
            deviceModelExportVO.setDepartmentName(DepartmentEnum.getValue(deviceModelVO.getDepartmentItemValue()));

            //素材模型编码
            deviceModelExportVO.setModelCoding(deviceModelVO.getModelCoding());

            //设置模型类别
            deviceModelExportVO.setModelCategory(ModelCategoryEnum.getValue(deviceModelVO.getModelCategory()));

            //设置是否启用
            deviceModelExportVO.setStatus(StatusEnum.getValue(String.valueOf(deviceModelVO.getStatus())));

            //设置排序
            deviceModelExportVO.setSeq(deviceModelVO.getSeq());

            return deviceModelExportVO;
        }).collect(Collectors.toList());

        //开始导出
        try{
            //构建文件名
            String fileName = "设备模型" + "_" + DateUtil.date() + ".xlsx";

            //设置响应体的内容类型 是excel的
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
            //设置响应体的响应头
            response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"utf-8"));
            //设置响应体的字符集
            response.setCharacterEncoding("UTF-8");

            //将相应结果转为输出流
            ServletOutputStream out = response.getOutputStream();

            //构造导出的数据 调用导出方法doWrite
            EasyExcel.write(out,DeviceModelExportVO.class)
                    .autoCloseStream(Boolean.TRUE)
                    .sheet()
                    .doWrite(data);

            //刷新输出流(一定要刷新不然不会生成excel)
            out.flush();
        }catch (Exception e){
            e.printStackTrace();
        }
    }


}
